<template>
  <!-- 养殖档案 -->
  <div class="page-content">
    <!-- 搜索栏组件 flag:等所有数据获取到 searchByType1data：基地 searchByType2data：养殖状态
          type2Name：档案和作业第二个分类搜索名称不一样，养殖档案：养殖状态-->
    <OperationsSearchBar v-if="flag" :searchByType1data="baseOptions" :searchByType2data="searchByType2data"
      :type2Name="type2Name" @getDataBySelectType2="getDataBySelectType2" @getDataBySelectTime="getDataBySelectTime"
      @getDataBySelectType1="getDataBySelectType1" @getDataByKeyword="getDataByKeyword" v-auth="'breed_product_select'">
    </OperationsSearchBar>
    <!-- 表格区域 -->
    <!-- 表格功能区 -->
    <div style="height: 20px; width:100%">
    </div>
    <TableBar :columns="columns" @changeColumn="changeColumn" :layout="layout">
      <div slot="bottom" style="width: 440px;">
        <el-row>
          <el-col :span="4">
            <el-button plain size="mini" type="primary" @click=" tableAdd_visible=true "
              v-auth="'breed_product_insert'">新增</el-button>
          </el-col>
          <el-col :span="4">
            <el-button plain size="mini" type="danger" @click="delDataBySelectBox" v-auth="'breed_product_delete'">删除
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-tooltip effect="dark" content="导入养殖档案EXCEL文件" placement="top-start">
              <el-upload action="http://120.77.156.205:9603/breed/farming-work/excel" :show-file-list="false">
                <el-button plain type="success" size="mini" @click="refresh">导入</el-button>
              </el-upload>
            </el-tooltip>
          </el-col>
          <el-col :span="5">
            <el-tooltip effect="dark" content="全部导出为EXCEL文件" placement="top-start">
              <el-button type="success" plain size="mini" @click="downLoadExcel">全部导出</el-button>
            </el-tooltip>
          </el-col>
          <!-- 部分导出，后端未完成，可后续增加 -->
          <!-- <el-col :span="5"
                ><el-tooltip
                  effect="dark"
                  content="选择导出为EXCEL文件"
                  placement="top-start"
                  ><el-button type="success" plain size="mini" @click="downLoadSelectExcel"
                  >选择导出</el-button
                ></el-tooltip></el-col> -->
        </el-row>
      </div>
    </TableBar>
    <!-- 表格数据 getDataBySelectBox：选中框数据 -->
    <TheTable :data="data" :page="page" ref="tableRef" @changeSize="changeSize" @changePage="changePage"
      :showPage="showPage" :Bottom="35" @getDataBySelectBox="getDataBySelectBox">
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <!-- 基地 -->
      <el-table-column :label="columns[2].name" v-if="columns[2].show" :prop="columns[2].prop" width="180">
      </el-table-column>
      <!-- 产品SKU -->
      <el-table-column :label="columns[3].name" v-if="columns[3].show" :prop="columns[3].prop" width="100">
      </el-table-column>
      <!-- 负责人 -->
      <el-table-column :label="columns[4].name" v-if="columns[4].show" :prop="columns[4].prop" width="100">
      </el-table-column>
      <!-- 养殖规模(只) -->
      <el-table-column :label="columns[5].name" v-if="columns[5].show" :prop="columns[5].prop" width="120">
      </el-table-column>
      <!-- 养殖状态 -->
      <el-table-column :label="columns[6].name" v-if="columns[6].show" :prop="columns[6].prop" width="80">
      </el-table-column>
      <!-- 养殖档案编号 -->
      <el-table-column :label="columns[0].name" v-if="columns[0].show" :prop="columns[0].prop" width="180">
      </el-table-column>
      <!-- 养殖开始时间 -->
      <el-table-column :label="columns[1].name" v-if="columns[1].show" :prop="columns[1].prop" width="200"
        :formatter="formatDate" sortable>
      </el-table-column>
      <!-- 备注 -->
      <el-table-column :label="columns[7].name" v-if="columns[7].show" :prop="columns[7].prop" width="180">
      </el-table-column>
      <!-- 操作 -->
      <el-table-column :label="columns[8].name" v-if="columns[8].show" width=auto min-width="240" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" plain @click="toOperations(scope.row.id)"
            v-auth="'breed_product_update'">作业</el-button>
          <el-button size="mini" type="primary" plain @click="tableEdit(scope.row)" v-auth="'breed_product_update'">编辑
          </el-button>
          <el-button size="mini" type="danger" plain @click="tableDelet(scope.row.id)" v-auth="'breed_product_delete'">
            删除</el-button>
        </template>
      </el-table-column>
    </TheTable>
    <!-- baseOptions养殖基地 SKUList产品SKU前面这些都是用于选择器
          finish：点击确定后执行finish刷新页面 -->
    <ProductionInfoTableEditForm v-show="tableEdit_visible" :editform="editform" :tableEdit_visible="tableEdit_visible"
      :baseOptions="baseOptions" :SKUList="SKUList" @closeEditDialog="closeEditDialog" @finish="finish">
    </ProductionInfoTableEditForm>
    <ProductionInfoTableAddForm v-show="tableAdd_visible" :tableAdd_visible="tableAdd_visible"
      :baseOptions="baseOptions" :SKUList="SKUList" @closeAddDialog="closeAddDialog" @finish="finish">
    </ProductionInfoTableAddForm>

  </div>

</template>

<script>
  // 搜索栏
  import OperationsSearchBar from '@/components/ProductionManagement/Operations/OperationsSearchBar'
  // 表格编辑表单弹窗
  import ProductionInfoTableEditForm from '@/components/ProductionManagement/ProductionInfo/ProductionInfoTableEditForm'
  // 表格新建表单弹窗
  import ProductionInfoTableAddForm from '@/components/ProductionManagement/ProductionInfo/ProductionInfoTableAddForm'
  // 接口数据
  import {
    getAllInfoByDate,
    searchProductionsKeyword,
    delProduction,
    delOneProduction,
    excelPutoutSelProduction,
    getColumns
    //   getAllInfoById,
  } from "../../Api/productionmanage/ProductionInfo"
  // 获取养殖档案Id
  import {
    formatDateToDialog
  } from "../../Api/productionmanage/Operations"
  // 获取基地信息
  import {
    getBaseInfo
  } from '@/Api/productionmanage/Breed_base'
  import {
    getSKU
  } from '@/Api/productionmanage/ProductManage'
  export default {
    name: 'ProductionInfo',
    components: {
      OperationsSearchBar,
      ProductionInfoTableEditForm,
      ProductionInfoTableAddForm
    },
    data() {
      return {
        // 搜索栏分类数据
        // 基地 baseOptions
        // 养殖状态 搜索框分类2选择器数据
        searchByType2data: [{
          value: 0,
          label: '全部',
        }, {
          value: 1,
          label: '养殖中',
        }, {
          value: 2,
          label: '已出栏',
        }],
        type2Name: "养殖状态",
        showPage: true,
        // 存放请求回来的数据
        data: [],
        // 表头
        columns: getColumns(),
        // 表格编辑表单显示与隐藏
        tableEdit_visible: false,
        tableAdd_visible: false,
        editform: {},
        // 传递给TheTable的数据
        page: {
          total: 0,
          pageSize: 10,
          current: 1,
        },
        // 表格选中框
        idBySelectBox: [],
        // 搜索内容（时间，类别，关键词）
        searchData: {
          startTime: null,
          overTime: null,
          farmingStatus: null,
          baseName: null,
        },
        // 表头右侧 即TableBar右侧要显示的功能按钮
        layout: 'refresh, column',
        baseOptions: [],
        // 产品SKU
        SKUList: [],
        // 子组件需要等父组件的数据
        flag: false,
        // 导入Excel
        putInfileList: [],
        // 选中多选框的信息列表
        selectedBoxList: [],
        // 关键词搜索
        keyWord: ""
      }
    },
    created() {
      this.getAllList();
      this.getBaseInfo();
      this.getSKUData();
    },
    methods: {
      // 查询所有数据
      async getAllList() {
        const {
          data: res
        } = await getAllInfoByDate(
          this.page.current,
          this.page.pageSize,
          this.searchData
        );
        if (res.statusCode == 20000) {
          if (res.data === null) {
            return this.$message.warning("搜索范围内无数据!");
          }
          this.data = res.data.records;
          this.page.total = parseInt(res.data.total);
          console.log("getAllList：" , this.data)
        } else {
          this.$message.error("查询养殖档案数据失败");
        }
      },
      // 搜索栏关键词查询数据
      async searchByKeyword(w) {
        console.log("keyword:" + w)
        if (w != undefined) {
          this.keyWord = w;
        }
        const {
          data: res
        } = await searchProductionsKeyword(
          this.page.current,
          this.page.pageSize,
          this.keyWord
        );
        if (res.statusCode == 20000) {
          if (res.data === null) {
            return this.$message.warning("搜索范围内无数据!");
          }
          this.data = res.data.records;
          console.log("searchByKeyword：" , this.data)
          this.page.total = parseInt(res.data.total);
          this.$message.success("查询养殖档案数据成功");
        } else {
          console.log("关键词查询失败" + res);
        }
      },
      // 删除单个养殖档案
      async tableDelet(a) {
        const {
          data: res
        } = await delOneProduction(a);
        if (res.statusCode == 20000) {
          this.$message('已成功删除该养殖档案');
          this.getAllList();
        } else {
          this.$message.error("删除该养殖档案失败");
        }
      },
      // 通过表格选择box批量删除养殖档案
      async delDataBySelectBox() {
        const {
          data: res
        } = await delProduction(this.idBySelectBox);
        if (res.statusCode == 20000) {
          this.$message('已成功删除选中的养殖档案');
          this.getAllList();
        } else {
          this.$message.error("删除该养殖档案失败");
        }
      },
      // 获取养殖基地数据
      async getBaseInfo() {
        await getBaseInfo(this.page).then(res => {
          if (res.data.statusCode !== 20000) {
            return this.$message.error('请求基地数据失败，请手动输入基地Id')
          }
          var arr = [];
          arr = res.data.data.records;
          for (let i = 0; i < arr.length; i++) {
            var obj = {
              label: "",
              value: ""
            };
            obj.label = arr[i].name;
            obj.value = arr[i].id;
            this.baseOptions.push(obj)
          }
        })
      },
      // 获取SKU数据
      async getSKUData() {
        await getSKU().then(res => {
          if (res.data.statusCode !== 20000) {
            return this.$message.error('请求SKU数据失败，请手动输入基地Id')
          }
          var arr = [];
          arr = res.data.data;
          for (let i = 0; i < arr.length; i++) {
            var obj = {
              label: "",
              value: ""
            };
            obj.label = arr[i];
            obj.value = i;
            this.SKUList.push(obj);
          }
          this.flag = true;
        })
      },
      // 点击养殖档案，跳转到养殖作业，显示相对应的养殖作业
      toOperations(id) {
        this.$router.push({
          path: '/BreedingManagement/Operations',
          query: {
            id: id
          }
        });
      },
      // 根据时间范围查询数据
      getDataBySelectTime(t) {
        if (t == null) {
          this.searchData.startTime = null;
          this.searchData.overTime = null;
        } else {
          var startTime = t[0];
          var overTime = t[1];
          this.searchData.startTime = startTime;
          this.searchData.overTime = overTime;
        }
        this.getAllList();
      },
      // 根据选择分类查询数据
      // 基地
      getDataBySelectType1(type) {
        if (type == "") {
          this.searchData.baseName = null;
        } else {
          this.searchData.baseName = type;
        }
        this.getAllList();
      },
      // 养殖状态 获取分类搜索选中数据
      getDataBySelectType2(type) {
        if (type.length == 0) {
          this.searchData.farmingStatus = null;
          this.searchData.baseName = null;
        } else {
          switch (type) {
            case "全部":
              this.searchData.farmingStatus = null;
              break;
            case "养殖中":
              this.searchData.farmingStatus = type
              break;
            case "已出栏":
              this.searchData.farmingStatus = type
              break;
            default:
              this.searchData.farmingStatus = null;
              this.$message.warning("根据养殖状态类型搜索失败");
              break;
          }
        }
        this.getAllList();
      },
      // 获取关键词
      getDataByKeyword(w) {
        if (w == "") {
          this.getAllList();
        } else {
          this.searchByKeyword(w);
        }
      },
      // 获取表格选中框
      getDataBySelectBox(w) {
        this.selectedBoxList = w;
        if (w.length == 0) {
          this.getAllList();
        } else {
          var arr = [];
          for (var i = 0; i < w.length; i++) {
            arr.push(w[i].id);
          }
          this.idBySelectBox = arr;
        }
      },
      // 新增编辑完成后获取最新数据
      finish() {
        this.page.current = 1;
        this.getAllList();
      },
      //导入Excel刷新
      refresh() {
        this.$refs.tableRef.getAllList();
      },
      // 导出EXCEL
      downLoadExcel() {
        let name = "养殖档案信息";
        window.location.href = `http://120.77.156.205:9603/breed/farming/excel/${name}`;
      },
      // 部分导出，后续可增加，后端还未完成
      // async downLoadSelectExcel() {
      //   let name = "excel";
      //   console.log(this.selectedBoxList);
      //   if (this.selectedBoxList.length == 0) {
      //     return this.$message.error("未选数据，无法导出EXCEL文件");
      //   }
      //   const {
      //     data: res
      //   } = await excelPutoutSelProduction(
      //     name,
      //     this.selectedBoxList
      //   );
      //   console.log(res);
      // },
      // 点击表格编辑按钮,传值到表单
      tableEdit(a) {
        a.farmingTime = formatDateToDialog(a.farmingTime);
        this.editform = a;
        this.tableEdit_visible = true;
      },
      // 表格编辑表单弹窗隐藏
      closeEditDialog(a) {
        this.tableEdit_visible = a;
        this.getAllList();
      },
      closeAddDialog(a) {
        this.tableAdd_visible = a;
        this.getAllList();
      },
      // 选择显示隐藏列
      changeColumn(newcolumns) {
        this.columns = newcolumns
      },
      // 分页 改变页码
      changePage(a) {
        this.page.current = a.current
        if (this.keyWord != "" && this.keyWord != undefined) {
          this.searchByKeyword();
        } else {
          this.getAllList();
        }
      },
      // 分页 改变每页显示的条数
      changeSize(a) {
        this.page.pageSize = a.pageSize
        if (this.keyWord != "" && this.keyWord != undefined) {
          this.searchByKeyword();
        } else {
          this.getAllList();
        }
      },
      // 格式化时间
      formatDate(row, column) {
        let a = row[column.property];
        return formatDateToDialog(a);
      },
    },
  }

</script>

<style>
</style>
